package com.coursehub.shared.transaction;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 分布式事务上下文
 */
@Slf4j
@Data
public class TransactionContext {
    
    /**
     * 事务ID
     */
    private final String transactionId;
    
    /**
     * 事务名称
     */
    private final String transactionName;
    
    /**
     * 事务状态
     */
    private TransactionStatus status;
    
    /**
     * 事务步骤列表
     */
    private final List<TransactionStep> steps;
    
    /**
     * 创建时间
     */
    private final LocalDateTime createTime;
    
    /**
     * 更新时间
     */
    private LocalDateTime updateTime;
    
    /**
     * 错误信息
     */
    private String errorMessage;
    
    public TransactionContext(String transactionId, String transactionName) {
        this.transactionId = transactionId;
        this.transactionName = transactionName;
        this.status = TransactionStatus.CREATED;
        this.steps = new ArrayList<>();
        this.createTime = LocalDateTime.now();
        this.updateTime = LocalDateTime.now();
    }
    
    /**
     * 添加事务步骤
     */
    public void addStep(TransactionStep step) {
        this.steps.add(step);
        this.updateTime = LocalDateTime.now();
        log.debug("事务 {} 添加步骤: {}", transactionId, step.getStepName());
    }
    
    /**
     * 更新事务状态
     */
    public void updateStatus(TransactionStatus status) {
        this.status = status;
        this.updateTime = LocalDateTime.now();
        log.debug("事务 {} 状态更新为: {}", transactionId, status);
    }
    
    /**
     * 设置错误信息
     */
    public void setError(String errorMessage) {
        this.errorMessage = errorMessage;
        this.updateTime = LocalDateTime.now();
        log.error("事务 {} 发生错误: {}", transactionId, errorMessage);
    }
    
    /**
     * 获取步骤数量
     */
    public int getStepCount() {
        return steps.size();
    }
    
    /**
     * 检查是否有步骤
     */
    public boolean hasSteps() {
        return !steps.isEmpty();
    }
}